import React, {PureComponent} from "react";
import {Button, Card, notification} from "antd";
import {connect} from "react-redux";
import {query} from "./actions";
import {Column, Line, measureTextWidth, Pie} from "@ant-design/plots";
import {getCurrentOrganization, getLastFilter} from "../../lib/identity";
import moment from "moment";
import lodash from 'lodash';

const LAST_FILTER = "profileAnal";

function renderStatistic(containerWidth, text, style) {
    const {width: textWidth, height: textHeight} = measureTextWidth(text, style);
    const R = containerWidth / 2; // r^2 = (w / 2)^2 + (h - offsetY)^2

    let scale = 1;

    if (containerWidth < textWidth) {
        scale = Math.min(Math.sqrt(Math.abs(Math.pow(R, 2) / (Math.pow(textWidth / 2, 2) + Math.pow(textHeight, 2)))), 1);
    }

    const textStyleStr = `width:${containerWidth}px;`;
    return `<div style="${textStyleStr};font-size:${scale}em;line-height:${scale < 1 ? 1 : 'inherit'};">${text}</div>`;
}

class List extends PureComponent {

    componentWillMount() {
        const {dispatch} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        dispatch(query({...fields, "year": moment().year().toString(), "organizationId": getCurrentOrganization()}));
    };

    exportFile = (fileName, fileData) => {
        document.getElementById("fileName").value = fileName;
        if (fileData && fileData.length > 0) {
            const headers = [];
            fileData.forEach(item => {
                for (let key in item) {
                    if (headers.indexOf(key) <= -1) {
                        headers.push(key);
                    }
                }
            });
            document.getElementById("headers").value = lodash.join(headers, ',');
            document.getElementById("rows").value = JSON.stringify(fileData);
            document.getElementById("exportFile").submit();
            notification.success({
                message: '请等待文件导出'
            });
        } else {
            notification.error({
                message: '没有数据可以导出'
            });
        }
    };


    render() {
        const {
            result, loading,
        } = this.props;

        /*const renderStatistic = (containerWidth, text, style) => {
            const {width: textWidth, height: textHeight} = measureTextWidth(text, style);
            const R = containerWidth / 2; // r^2 = (w / 2)^2 + (h - offsetY)^2

            let scale = 1;

            if (containerWidth < textWidth) {
                scale = Math.min(Math.sqrt(Math.abs(Math.pow(R, 2) / (Math.pow(textWidth / 2, 2) + Math.pow(textHeight, 2)))), 1);
            }

            const textStyleStr = `width:${containerWidth}px;`;
            return `<div style="${textStyleStr};font-size:${scale}em;line-height:${scale < 1 ? 1 : 'inherit'};">${text}</div>`;
        };*/

        // 综合物流 饼图
        const zhwlData = [];
        let ghOrderCount = 0;
        const orderTypeCount = result['orderTypeCount'] || [];
        orderTypeCount.forEach(item => {
            /*if (item.name !== "总单量" && item.name !== "提货线路" && item.name !== "派送线路") {
                zhwlData.push({"name": item.name, "count": item.count});
            }*/
            if(item.name === "总单量"){
                ghOrderCount = item.count;
            }
            if (item.name !== "总单量") {
                zhwlData.push({"name": item.name, "count": item.count});
            }
        });
        const zhwuPieConfig = {
            appendPadding: 10,
            data: zhwlData,
            angleField: 'count',
            colorField: 'name',
            radius: 1,
            innerRadius: 0.64,
            meta: {
                value: {
                    formatter: (v) => `${v}`,
                },
            },
            label: {
                type: 'inner', offset: '-50%', style: {
                    textAlign: 'center',
                }, autoRotate: false, content: '{value}',
            },
            statistic: {
                title: {
                    offsetY: -4, customHtml: (container, view, datum) => {
                        const {width, height} = container.getBoundingClientRect();
                        const d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
                        const text = datum ? datum.type : '总计';
                        return renderStatistic(d, text, {
                            fontSize: 28,
                        });
                    },
                }, content: {
                    offsetY: 4, style: {
                        fontSize: '32px',
                    }, customHtml: (container, view, datum, data) => {
                        const {width} = container.getBoundingClientRect();
                        const text = datum ? `${datum.value}` : `${data.reduce((r, d) => r + d.value, 0)}`;
                        return renderStatistic(width, text, {
                            fontSize: 32,
                        });
                    },
                },
            }, // 添加 中心统计文本 交互
            interactions: [{
                type: 'element-selected',
            }, {
                type: 'element-active',
            }, {
                type: 'pie-statistic-active',
            },],
        };
        // 仓储 饼图
        const ccData = [];
        let ccGhOrderCount = 0;
        const commodityCount = result['commodityCount'] || [];
        commodityCount.forEach(item => {
            if (item.name !== "总单量") {
                ccData.push({"name": item.name, "count": item.count});
            }
            if (item.name === "总单量") {
                ccGhOrderCount = item.count;
            }
        });
        const ccPieConfig = {
            appendPadding: 10,
            data: ccData,
            angleField: 'count',
            colorField: 'name',
            radius: 1,
            innerRadius: 0.64,
            meta: {
                value: {
                    formatter: (v) => `${v}`,
                },
            },
            label: {
                type: 'inner', offset: '-50%', style: {
                    textAlign: 'center',
                }, autoRotate: false, content: '{value}',
            },
            statistic: {
                title: {
                    offsetY: -4, customHtml: (container, view, datum) => {
                        const {width, height} = container.getBoundingClientRect();
                        const d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
                        const text = datum ? datum.type : '总计';
                        return renderStatistic(d, text, {
                            fontSize: 28,
                        });
                    },
                }, content: {
                    offsetY: 4, style: {
                        fontSize: '32px',
                    }, customHtml: (container, view, datum, data) => {
                        const {width} = container.getBoundingClientRect();
                        const text = datum ? `${datum.value}` : `${data.reduce((r, d) => r + d.value, 0)}`;
                        return renderStatistic(width, text, {
                            fontSize: 32,
                        });
                    },
                },
            }, // 添加 中心统计文本 交互
            interactions: [{
                type: 'element-selected',
            }, {
                type: 'element-active',
            }, {
                type: 'pie-statistic-active',
            },],
        };
        // 综合物流 提货
        const zhwlPickLine = [];
        const pickLineCount = result['pickLineCount'] || [];
        pickLineCount.forEach(item => {
            zhwlPickLine.push({"名称": item.name, "总数": item.count});
        });
        const zhwlPickLineConfig = {
            data: zhwlPickLine, xField: '名称', yField: '总数', label: {
                // 可手动配置 label 数据标签位置
                position: 'middle', // 'top', 'bottom', 'middle',
                // 配置样式
                style: {
                    fill: '#FFFFFF', opacity: 0.6,
                },
            }, xAxis: {
                label: {
                    autoHide: true, autoRotate: false,
                },
            }, meta: {
                type: {
                    alias: '综合物流 始发地',
                }, sales: {
                    alias: '单量',
                },
            },
        };
        // 仓储 提货
        const ccPickLine = [];
        const pickLineOrderCount = result['pickLineOrderCount'] || [];
        pickLineOrderCount.forEach(item => {
            ccPickLine.push({"名称": item.name, "总数": item.count});
        });
        const ccPickLineConfig = {
            data: ccPickLine, xField: '名称', yField: '总数', label: {
                // 可手动配置 label 数据标签位置
                position: 'middle', // 'top', 'bottom', 'middle',
                // 配置样式
                style: {
                    fill: '#FFFFFF', opacity: 0.6,
                },
            }, xAxis: {
                label: {
                    autoHide: true, autoRotate: false,
                },
            }, meta: {
                type: {
                    alias: '仓储 始发地',
                }, sales: {
                    alias: '单量',
                },
            },
        };
        // 综合物流 目的地
        const zhwlEndLine = [];
        const destPlaceCount = result['destPlaceCount'] || [];
        destPlaceCount.forEach(item => {
            zhwlEndLine.push({"名称": item.name, "总数": item.count});
        });
        const zhwlEndLineConfig = {
            data: zhwlEndLine, xField: '名称', yField: '总数', label: {
                // 可手动配置 label 数据标签位置
                position: 'middle', // 'top', 'bottom', 'middle',
                // 配置样式
                style: {
                    fill: '#FFFFFF', opacity: 0.6,
                },
            }, xAxis: {
                label: {
                    autoHide: true, autoRotate: false,
                },
            }, meta: {
                type: {
                    alias: '综合物流 目的地',
                }, sales: {
                    alias: '单量',
                },
            },
        };
        // 综合物流 目的地
        const ccEndLine = [];
        const destPlaceOrderCount = result['destPlaceOrderCount'] || [];
        destPlaceOrderCount.forEach(item => {
            ccEndLine.push({"名称": item.name, "总数": item.count});
        });
        const ccEndLineConfig = {
            data: ccEndLine, xField: '名称', yField: '总数', label: {
                // 可手动配置 label 数据标签位置
                position: 'middle', // 'top', 'bottom', 'middle',
                // 配置样式
                style: {
                    fill: '#FFFFFF', opacity: 0.6,
                },
            }, xAxis: {
                label: {
                    autoHide: true, autoRotate: false,
                },
            }, meta: {
                type: {
                    alias: '仓储 目的地',
                }, sales: {
                    alias: '单量',
                },
            },
        };
        // 综合物流饼图
        const ZhwlPie = () => {
            const config = {
                appendPadding: 10,
                data: zhwlData,
                angleField: 'count',
                colorField: 'name',
                radius: 0.9,
                meta: {
                    value: {
                        formatter: (v) => `${v}`,
                    },
                },
            };
            return <Pie {...config} />;
        };
        // 仓储饼图
        const CcPie = () => {
            const config = {
                appendPadding: 10,
                data: ccData,
                angleField: 'count',
                colorField: 'name',
                radius: 0.8,
                meta: {
                    value: {
                        formatter: (v) => `${v}`,
                    },
                },
            };
            return <Pie {...config} />;
        };
        return (<div>
            <div className="line1">

                <Card style={{width: "45%", float: "left"}}
                      title={"综合物流 总单量"+ghOrderCount+"票"} extra={<Button onClick={() => this.exportFile("综合物流", zhwlData)}>导出</Button>}>
                    <ZhwlPie/>
                </Card>
                <Card style={{width: "45%", float: "left", marginLeft: "10px"}}
                      title={"仓储 总单量"+ccGhOrderCount+"票"} extra={<Button onClick={() => this.exportFile("仓储", ccData)}>导出</Button>}>
                    <CcPie/>
                </Card>
            </div>
            <div className="line2">
                <Card style={{width: "45%", float: "left"}}
                      title="综合物流 始发地 单位：票"
                      extra={<Button onClick={() => this.exportFile("综合物流 始发地", zhwlPickLine)}>导出</Button>}>
                    <Column {...zhwlPickLineConfig} />
                </Card>
                <Card style={{width: "45%", float: "left", marginLeft: "10px"}}
                      title="仓储 始发地 单位：票" extra={<Button onClick={() => this.exportFile("仓储 始发地", ccPickLine)}>导出</Button>}>
                    <Column {...ccPickLineConfig} />
                </Card>
            </div>
            <div className="line2">
                <Card style={{width: "45%", float: "left"}}
                      title="综合物流 目的地 单位：票"
                      extra={<Button onClick={() => this.exportFile("综合物流 目的地", zhwlEndLine)}>导出</Button>}>
                    <Column {...zhwlEndLineConfig} />
                </Card>
                <Card style={{width: "45%", float: "left", marginLeft: "10px"}}
                      title="仓储 目的地 单位：票" extra={<Button onClick={() => this.exportFile("仓储 目的地", ccEndLine)}>导出</Button>}>
                    <Column {...ccEndLineConfig} />
                </Card>
            </div>
            <form
                id="exportFile"
                method="post"
                target="_blank"
                action="/api/orderAnalysis/commonExport"
            >
                <input
                    id="fileName"
                    name="fileName"
                    type="hidden"
                />
                <input
                    id="rows"
                    name="rows"
                    type="hidden"
                />
                <input
                    id="headers"
                    name="headers"
                    type="hidden"
                />
            </form>
        </div>);
    }
}

const mapStateToProps = state => {
    return {
        ...state.profitAnal.list
    };
};

export default connect(mapStateToProps)(List);
